using System;
using System.Net;
using System.Net.Sockets;

namespace Fusion.Net.UDP
{
    public abstract class UDPSocket : SocketBase
    {
        protected UDPNet udp;

        protected EndPoint targetIP;

        protected int bufferSize = NetConfig.UDP_Buffer_Size;
        protected byte[] buffer;

        public UDPSocket(UDPNet udp, Socket socket) : base(udp, socket)
        {
            this.udp = udp;
            buffer = new byte[bufferSize];
        }

        public UDPSocket(UDPNet udp, AddressFamily addressFamily) : base(udp, addressFamily, SocketType.Dgram, ProtocolType.Udp)
        {
            this.udp = udp;
            buffer = new byte[bufferSize];
        }

        public EndPoint TargetIP { get => targetIP; set => targetIP = value; }
        protected UDPNet UDP { get => udp;}

        public override byte[] Pack(byte[] data, int length)
        {
            if (data.Length == length)
            {
                return data;
            }
            byte[] result = new byte[length];
            Array.Copy(data, result, length);
            return result;
        }

        public override void Send(byte[] data, int length)
        {
            if (TargetIP == null)
                return;
            data = Pack(data, length);

            if (data.Length > bufferSize)
            {
                return;
            }

            Send(data, TargetIP);
        }

        public void ClearCaches(EndPoint ip)
        {
            ClearCaches(ip.ToString());
        }

        public virtual void ClearCaches(string ip)
        {
        }

        public void Send(byte[] data, EndPoint ip)
        {
            try
            {
                socket.SendTo(data, ip);
            }
            catch (SocketException e)
            {
                HandleError(e);
            }
            catch (ObjectDisposedException e)
            {
                HandleError(e);
            }
        }

        protected override void PreOpen()
        {
            socket.Bind(ip);
        }
    }
}


